<template>
  <div class="age-spending-page">
    <!-- 顶部信息卡片 -->
    <div class="info-card">
      <div class="info-content">
        <!-- 左侧图片 -->
        <div class="info-image">
          <img src="/banner2.jpg" alt="年龄消费分析" />
        </div>
        <!-- 右侧文字 -->
        <div class="info-text">
          <h2>
            📊 不同年龄段平均消费分析
          </h2>
          <p class="desc">
            本图表展示了 15-55 岁不同年龄段用户的平均消费金额情况，
            以不同年龄段用户的平均消费金额进行可视化展示。
          </p>
        </div>
      </div>
    </div>

    <!-- 图表卡片 -->
    <div class="chart-card">
      <div class="chart-container" ref="chartRef"></div>
      <p class="note">提示：柱形图表示平均消费金额（元）</p>
    </div>

    <!-- 下载按钮 -->
    <div class="download-wrapper">
      <button class="download-btn" @click="downloadChart">下载图表文件</button>
    </div>

    <!-- 页面底部 Footer -->
    <FooterInfo />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import FooterInfo from '../components/FooterInfo.vue'
import axios from 'axios'

const minAge = ref(15)
const maxAge = ref(19)

const chartRef = ref(null)
let chartInstance = null
const chartData = ref([])

// 固定的年龄区间
const ageRanges = [
  '15-19', '20-24', '25-29',
  '30-34', '35-39', '40-44',
  '45-49', '50-55'
]

// 初始化空图表
onMounted(async () => {
  await nextTick()
  const el = chartRef.value
  if (!el) return
  chartInstance = echarts.init(el)
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['平均消费金额'] },
    xAxis: { type: 'category', data: [] },
    yAxis: { type: 'value', name: '平均消费金额 (元)' },
    series: []
  })

  // 页面加载时直接请求所有区间数据
  await fetchAllData()
})

// 批量获取所有区间数据
async function fetchAllData() {
  try {
    const results = await Promise.all(
      ageRanges.map(async (range) => {
        const res = await axios.get('http://localhost:8080/queryAvgConsumptionOfAge', { params: { age: range } })

        if (res.data.code === 200) {
          return {
            ageRange: range,
            avgAmount: res.data.data?.avgConsumption || 0
          }
        } else {
          return { ageRange: range, avgAmount: 0 }
        }
      })
    )

    chartData.value = results
    updateChart()
  } catch (err) {
    console.error(err)
    alert('获取数据失败，请检查接口！')
  }
}

async function fetchData() {
  if (minAge.value > maxAge.value) {
    alert('最小年龄不能大于最大年龄！')
    return
  }
  const ageRange = `${minAge.value}-${maxAge.value}`
  console.log('fetchData 已弃用，参数：', ageRange)
}

// 更新图表
function updateChart() {
  if (!chartInstance || !chartData.value.length) return

  chartInstance.setOption({
    xAxis: {
      data: chartData.value.map(d => d.ageRange)
    },
    series: [
      {
        name: '平均消费金额',
        type: 'bar',
        data: chartData.value.map(d => d.avgAmount),
        itemStyle: { color: '#4a90e2' }
      }
    ]
  })
}

// 下载图表
function downloadChart() {
  if (!chartInstance) return
  const url = chartInstance.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff'
  })
  const link = document.createElement('a')
  link.href = url
  link.download = 'age-spending-chart.png'
  link.click()
}
</script>

<style scoped>
.age-spending-page {
  max-width: 1000px;
  margin: 40px auto;
  font-family: 'Segoe UI', sans-serif;
}

/* 顶部信息卡片 */
.info-card {
  background: #fff;
  padding: 25px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  margin-bottom: 25px;
}

.info-content {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.info-image img {
  width: 240px;
  height: auto;
  border-radius: 8px;
  object-fit: cover;
  margin-top: 70px;
}

.info-text {
  flex: 1;
}

.info-text h2 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.info-text .desc {
  font-size: 15px;
  color: #555;
  line-height: 1.8;
  text-align: justify;
}

.param-card {
  display: none;
}

/* 图表卡片 */
.chart-card {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.note {
  text-align: center;
  font-size: 13px;
  color: #888;
  margin-top: 10px;
}

/* 下载按钮 */
.download-wrapper {
  text-align: center;
  margin-bottom: 30px;
}

.download-btn {
  background: #ff7f50;
  color: #fff;
  padding: 10px 22px;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.3s;
}

.download-btn:hover {
  background: #ff6333;
}
</style>
